package com.gfxy.modules.items.controller;

import java.io.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gfxy.modules.GfxyUtils;
import com.gfxy.modules.common.entity.MemberSimpleList;
import com.gfxy.modules.items.service.DictTranslater;
import com.gfxy.modules.items.vo.InnovationAndEntrepreneurshipMemberPage;
import com.gfxy.modules.excel.TemplateUtil;
import org.jeecg.common.api.vo.Result;
import com.gfxy.modules.common.entity.MemberList;
import com.gfxy.modules.items.entity.InnovationAndEntrepreneurship;
import com.gfxy.modules.items.vo.InnovationAndEntrepreneurshipPage;
import com.gfxy.modules.items.service.IInnovationAndEntrepreneurshipService;
import com.gfxy.modules.common.service.IMemberListService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 创新创业大赛
 * @Author: jeecg-boot
 * @Date:   2021-06-29
 * @Version: V1.0
 */
@Api(tags="创新创业大赛")
@RestController
@RequestMapping("/teaching/innovationAndEntrepreneurship")
@Slf4j
public class InnovationAndEntrepreneurshipController {
	@Autowired
	private IInnovationAndEntrepreneurshipService innovationAndEntrepreneurshipService;
	@Autowired
	private IMemberListService memberListService;

	 @Autowired
	 private DictTranslater dictTranslater;

	 @Autowired
	 private TemplateUtil templateUtil;

	/**
	 * 分页列表查询
	 *

	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
//	@AutoLog(value = "创新创业大赛-分页列表查询")
//	@ApiOperation(value="创新创业大赛-分页列表查询", notes="创新创业大赛-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<?> queryPageList(InnovationAndEntrepreneurship innovationAndEntrepreneurship,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//
//		return Result.OK(null);
//	}

	 @AutoLog(value = "创新创业大赛-分页列表查询")
	 @ApiOperation(value="创新创业大赛-分页列表查询", notes="创新创业大赛-分页列表查询")
	 @GetMapping(value = "/listInYear")
	 public Result<?> queryPageList(
			 @RequestParam(name="date")  String date,
			 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			 HttpServletRequest req) {

		 String rolesStr = GfxyUtils.getRoles(req);


		 IPage<InnovationAndEntrepreneurshipMemberPage> list = innovationAndEntrepreneurshipService.getZxjpkMemberPageListByYear(date, pageNo, pageSize);

		 return Result.OK(list);

	 }

	 private boolean hasTeachingApprovePermission(String rolesStr){
		 return rolesStr.contains("teaching_approve");
	 }

	/**
	  *   添加
	  *
	  * @param innovationAndEntrepreneurshipPage
	  * @return
	  */
	 @AutoLog(value = "创新创业大赛-添加")
	 @ApiOperation(value="创新创业大赛-添加", notes="创新创业大赛-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody InnovationAndEntrepreneurshipPage innovationAndEntrepreneurshipPage) {
		 InnovationAndEntrepreneurship innovationAndEntrepreneurship = new InnovationAndEntrepreneurship();
		 BeanUtils.copyProperties(innovationAndEntrepreneurshipPage, innovationAndEntrepreneurship);
		 innovationAndEntrepreneurshipService.saveMain(innovationAndEntrepreneurship, innovationAndEntrepreneurshipPage.getMemberListList());
		 return Result.OK("添加成功！");
	 }

	 /**
	 *  编辑
	 *
	 * @param innovationAndEntrepreneurshipPage
	 * @return
	 */
	@AutoLog(value = "创新创业大赛-编辑")
	@ApiOperation(value="创新创业大赛-编辑", notes="创新创业大赛-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody InnovationAndEntrepreneurshipPage innovationAndEntrepreneurshipPage) {
		InnovationAndEntrepreneurship innovationAndEntrepreneurship = new InnovationAndEntrepreneurship();
		BeanUtils.copyProperties(innovationAndEntrepreneurshipPage, innovationAndEntrepreneurship);
		InnovationAndEntrepreneurship innovationAndEntrepreneurshipEntity = innovationAndEntrepreneurshipService.getById(innovationAndEntrepreneurship.getId());
		if(innovationAndEntrepreneurshipEntity==null) {
			return Result.error("未找到对应数据");
		}
		innovationAndEntrepreneurshipService.updateMain(innovationAndEntrepreneurship, innovationAndEntrepreneurshipPage.getMemberListList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "创新创业大赛-通过id删除")
	@ApiOperation(value="创新创业大赛-通过id删除", notes="创新创业大赛-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		innovationAndEntrepreneurshipService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "创新创业大赛-批量删除")
	@ApiOperation(value="创新创业大赛-批量删除", notes="创新创业大赛-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.innovationAndEntrepreneurshipService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "创新创业大赛-通过id查询")
	@ApiOperation(value="创新创业大赛-通过id查询", notes="创新创业大赛-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		InnovationAndEntrepreneurship innovationAndEntrepreneurship = innovationAndEntrepreneurshipService.getById(id);
		if(innovationAndEntrepreneurship==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(innovationAndEntrepreneurship);

	}



    /**
    * 导出excel
    *
    * @param request
    * @param innovationAndEntrepreneurship
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InnovationAndEntrepreneurship innovationAndEntrepreneurship) throws NoSuchFieldException {
		try{
			List<InnovationAndEntrepreneurshipMemberPage> innovation = new ArrayList<>();
			String rolesStr = GfxyUtils.getRoles(request);
			String year = innovationAndEntrepreneurship.getDate();
//			if(this.hasTeachingApprovePermission(rolesStr)){
//				innovation = innovationAndEntrepreneurshipService.innovationAndEntrepreneurListByYear(year);
//			} else {
//				String orgCode = GfxyUtils.getOrgCode(request);
//				innovation = innovationAndEntrepreneurshipService.getInnovationAndEntrepreneurshipMemberPageListByYearAndOrgCode(year,orgCode);
//			}
			innovation=innovationAndEntrepreneurshipService.getZxjpkMemberPageListByYear(year);

			List<String> title = new ArrayList<>();
			title.add("年份");
			title.add("项目名称");
			title.add("级别");
			title.add("组别");
			title.add("奖项");
			title.add("成员");

			List<List<String>> contents = new ArrayList<>();
			for (InnovationAndEntrepreneurshipMemberPage innovationPage : innovation) {
				List<String> content = new ArrayList<>();
				content.add(innovationPage.getDate());
				content.add(dictTranslater.getDictValue(InnovationAndEntrepreneurshipMemberPage.class, "matchClassess", String.valueOf(innovationPage.getMatchClassess())));
				content.add(dictTranslater.getDictValue(InnovationAndEntrepreneurshipMemberPage.class, "matchGroup", String.valueOf(innovationPage.getMatchGroup())));
				content.add(dictTranslater.getDictValue(InnovationAndEntrepreneurshipMemberPage.class, "award", String.valueOf(innovationPage.getAward())));
				content.add(innovationPage.getProjectName());

				List<MemberSimpleList> list = innovationPage.getMemberListList();
				StringBuffer names = new StringBuffer();
				for (MemberSimpleList memberSimpleList : list) {
					names.append(memberSimpleList.getUserName()).append("、");
				}
				content.add(names.toString());
				contents.add(content);
			}


			ModelAndView mv = new ModelAndView(new TeachingExcelView());
			mv.addObject(TeachingExcelView.FILE_NAME,"互联网+大赛-" + year);
			mv.addObject(TeachingExcelView.TITLE, title);
			mv.addObject(TeachingExcelView.CONTENT, contents);
			return mv;
		} catch (Exception e){
			throw e;
		}
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
		  try {

			  return Result.OK(innovationAndEntrepreneurshipService.importExcel(file));
		  } catch (IOException e) {
			  log.error(e.getMessage(),e);
			  return Result.error("文件导入失败:"+e.getMessage());
		  } finally {
			  try {
				  file.getInputStream().close();
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "成员列表通过主表ID查询")
	 @ApiOperation(value="成员列表主表ID查询", notes="成员列表-通主表ID查询")
	 @GetMapping(value = "/queryMemberListByMainId")
	 public Result<?> queryMemberListListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<MemberList> memberListList = memberListService.selectByItemId(id);
		 return Result.OK(memberListList);
	 }

	 @AutoLog(value = "创新创业大赛-审批")
	 @ApiOperation(value="创新创业大赛-审批", notes="创新创业大赛-审批")
	 @DeleteMapping(value = "/pass")
	 public Result<?> queryPageList(@RequestParam(name="ids",required=true) String ids) {
		 this.innovationAndEntrepreneurshipService.passBatch(Arrays.asList(ids.split(",")),"1");
		 return Result.OK("审核成功");
	 }

	 @AutoLog(value = "创新创业大赛-获取总分")
	 @ApiOperation(value="创新创业大赛-获取总分", notes="创新创业大赛-获取总分")
	 @GetMapping(value = "/getTotalScore")
	 public Result<?> getTotalScore(@RequestParam(name="matchClassess", defaultValue="0")  Integer matchClassess,
									@RequestParam(name="award", defaultValue="0") Integer award,
									HttpServletRequest req) {
		 InnovationAndEntrepreneurship innovationAndEntrepreneurship = new InnovationAndEntrepreneurship();
		 innovationAndEntrepreneurship.setMatchClassess(matchClassess);
		 innovationAndEntrepreneurship.setAward(award);
		 Double result = this.innovationAndEntrepreneurshipService.getTotalScore(innovationAndEntrepreneurship);
		 return Result.OK(result);
	 }

	 @GetMapping(value = "/handleExportXlsTemplate")
	 public Result<?> download(HttpServletRequest request, HttpServletResponse response)  {

		 try {
			 templateUtil.template(response,TemplateUtil.KLW);
		 } catch (IOException e) {
			 e.printStackTrace();
			 return  Result.error("下载失败");
		 }
		 return  Result.OK("下载成功");
	 }

}
